package com.server;

import java.io.*;
import java.net.URLConnection;

/**
 * @author lulei
 * @date 2020年12月25日 18:40:50
 */
public class MyClassLoader extends ClassLoader{
    public Class<?> getClass(String name) throws ClassNotFoundException {
        byte[] data=null;
        try {
            data = this.loadClassFile(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.defineClass(name, data, 0, data.length);
    }

    /**
     * 从磁盘加载
     * @param name
     * @return
     * @throws Exception
     */
    public byte[] loadClassFile(String name) throws Exception{
        String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
        String filePath = "D:"+File.separator+fileName;
        File file=new File(filePath);
        InputStream input=new FileInputStream(file);
        ByteArrayOutputStream baos = inputStreamToBytes(input);
        return baos.toByteArray();
    }



    private ByteArrayOutputStream inputStreamToBytes(InputStream input) throws IOException {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        //必须定义byte数组才能使用InputStream
        byte[] data=new byte[1024];
        int len=0;//读取的个数
        while((len=input.read(data))!=-1){
            baos.write(data,0,len);
        }
        input.close();
        baos.close();
        return baos;
    }
}
